"""
Case Type   : 数据库系统
Case Name   : 创建索引过程中在事务外对相关表进行update操作
Create At   : 2023/8/2
Owner       : @li-xin12345
Description :
    1.创建表，并插入大数据
    2.使用concurrently创建索引
    3.在创建索引的同时对表进行insert操作
    4.使用explain检查索引可否正常使用
    5.查询新插入数据
Expect      :
    1.创建表并插入大数据成功
    2.创建索引成功
    3.insert操作无阻塞，插入数据成功
    4.索引可正常使用
    5.可查询到新插入数据
History     :
"""
import os
import unittest

from yat.test import Node
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class Concurrently(unittest.TestCase):
    primary_sh = CommonSH('PrimaryDbUser')

    def setUp(self):
        self.dbPrimaryDbUser = Node(node='PrimaryDbUser')
        self.log = Logger()
        self.Constant = Constant()
        self.tblname = 'ddl_index_case0212'
        self.idxname = 'ddl_index_case0212_idx'
        self.value = 1000000
        self.log.info(f'-----{os.path.basename(__file__)} start-----')

    def test_in_select(self):
        self.log.info('------create table------')
        result = self.primary_sh.execut_db_sql(
            f'DROP TABLE IF EXISTS {self.tblname};'
            f'CREATE TABLE {self.tblname}(id INT, '
            f'first_name text, last_name text);')
        self.log.info(result)
        self.assertIn(self.Constant.CREATE_TABLE_SUCCESS, result)
        self.log.info('---------insert data-------------')
        result = self.primary_sh.execut_db_sql(
            f"INSERT INTO {self.tblname} SELECT id, md5(random()::text), "
            f"md5(random()::text) FROM ("
            f"SELECT * FROM generate_series(1,{self.value}) AS id) AS x;"
            f"update {self.tblname} set first_name='测试查询不阻塞', "
            f"last_name='测试%%不阻塞' where id = 712;")
        self.log.info(result)
        self.assertIn(self.Constant.INSERT_SUCCESS_MSG, result)
        self.assertIn(self.Constant.UPDATE_SUCCESS_MSG, result)

        self.log.info('-------create index--------')
        sql = f'select current_time;' \
              f'create index concurrently {self.idxname} on {self.tblname} ' \
              f'USING btree(id);select current_time;'
        create_index_thread = ComThread(self.primary_sh.execut_db_sql,
                                        args=(sql, ''))
        create_index_thread.setDaemon(True)
        create_index_thread.start()

        self.log.info('------ insert table-------')
        before_time = self.dbPrimaryDbUser.sh("date +'%s'").result()
        result = self.primary_sh.execut_db_sql(
            f'insert into {self.tblname} values('
            f'200000001,\'^c test 号\',\'\\test--\'); ')
        after_time = self.dbPrimaryDbUser.sh("date +'%s'").result()
        self.log.info(result)
        self.assertIn(self.Constant.INSERT_SUCCESS_MSG, result)
        total_time = int(after_time) - int(before_time)
        self.log.info(f'before_time is : {before_time}')
        self.log.info(f'after_time is : {after_time}')

        self.log.info('------check create index result--------')
        create_index_thread.join(10 * 60)
        create_idx_result = create_index_thread.get_result()
        self.log.info(create_idx_result)
        self.assertIn(self.Constant.CREATE_INDEX_SUCCESS, create_idx_result)
        before_create_time = create_idx_result.splitlines()[2].strip()
        after_create_time = create_idx_result.splitlines()[-2].strip()
        self.log.info(f'before_create_time is {before_create_time}')
        self.log.info(f'after_create_time is {after_create_time}')
        create_time_H = before_create_time.split(':')[0]
        create_time_M = before_create_time.split(':')[1]
        create_time_S = before_create_time.split(':')[2].split('.')[0]
        create_time_H1 = after_create_time.split(':')[0]
        create_time_M1 = after_create_time.split(':')[1]
        create_time_S1 = after_create_time.split(':')[2].split('.')[0]
        create_index_time = int(create_time_H1) * 60 * 60 + \
                            int(create_time_M1) * 60 + \
                            int(create_time_S1) - \
                            int(create_time_H) * 60 * 60 - \
                            int(create_time_M) * 60 - int(create_time_S)
        self.log.info(f'create_index_time is {create_index_time}')
        self.assertIn(self.Constant.CREATE_INDEX_SUCCESS, create_idx_result)
        self.log.info('若阻塞插入时间必然比创建索引时间大')
        self.assertGreaterEqual(create_index_time, total_time,
                                "执行失败：创建索引阻塞")

        self.log.info('-----show idx----------')
        sql = f'set enable_seqscan=off;' \
              f'explain select * from {self.tblname} where id=200000001;'
        result = self.primary_sh.execut_db_sql(sql)
        self.log.info(result)
        self.assertIn(self.idxname, result)

        self.log.info('-----select new data---------')
        sql = f'set enable_seqscan=off;' \
              f'select * from {self.tblname} where id=200000001;'
        result = self.primary_sh.execut_db_sql(sql)
        self.log.info(result)

        self.assertIn('200000001', result)
        self.assertIn('^c test 号', result)
        self.assertIn('\\test--', result)

    def tearDown(self):
        self.log.info('--------this is tearDown----------')
        self.log.info('---------drop table-------------')
        sql = f'drop table if exists {self.tblname};'
        result = self.primary_sh.execut_db_sql(sql)
        self.log.info(result)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
